const Database = require('better-sqlite3');
const path = require('path');
const {app} = require('@electron/remote');
import {logger} from '@/utils/logger';

class MesLogger {
    constructor() {
        this.dbPath = path.join(app.getPath('userData'), 'mes_logs.db');
        this.db = null;
        this.init();
    }

    init() {
        try {
            this.db = new Database(this.dbPath);
            logger.info(`数据库连接成功: ${this.dbPath}`);

            // 创建MES日志表
            this.db.exec(`
                CREATE TABLE IF NOT EXISTS mes_logs
                (
                    id
                    INTEGER
                    PRIMARY
                    KEY
                    AUTOINCREMENT,
                    timestamp
                    TEXT
                    NOT
                    NULL,
                    event_type
                    TEXT
                    NOT
                    NULL,
                    result
                    BOOLEAN
                    NOT
                    NULL,
                    message
                    TEXT,
                    request_data
                    TEXT,
                    response_data
                    TEXT
                )
            `);

            // 创建索引以提高查询性能
            this.db.exec(`
                CREATE INDEX IF NOT EXISTS idx_mes_logs_timestamp ON mes_logs(timestamp);
                CREATE INDEX IF NOT EXISTS idx_mes_logs_event_type ON mes_logs(event_type);
                CREATE INDEX IF NOT EXISTS idx_mes_logs_result ON mes_logs(result);
            `);

        } catch (error) {
            logger.error(`数据库初始化失败: ${error.message}`);
        }
    }

    // 记录MES交互日志
    logMesInteraction(eventType, result, message, requestData, responseData) {
        try {
            const stmt = this.db.prepare(`
                INSERT INTO mes_logs (timestamp, event_type, result, message, request_data, response_data)
                VALUES (datetime('now', 'localtime'), ?, ?, ?, ?, ?)
            `);
            const info = stmt.run(
                eventType,
                result,
                message || '',
                JSON.stringify(requestData || {}),
                JSON.stringify(responseData || {})
            );

            logger.info(`[MES日志] 已记录事件 ${eventType}, ID: ${info.lastInsertRowid}`);
            return info.lastInsertRowid;
        } catch (error) {
            logger.error(`[MES日志] 记录失败: ${error.message}`);
            return null;
        }
    }

    // 获取所有MES日志
    getAllMesLogs() {
        try {
            const stmt = this.db.prepare('SELECT * FROM mes_logs ORDER BY timestamp DESC');
            return stmt.all();
        } catch (error) {
            logger.error(`[MES日志] 获取失败: ${error.message}`);
            return [];
        }
    }

    // 根据ID获取MES日志详情
    getMesLogById(id) {
        try {
            const stmt = this.db.prepare('SELECT * FROM mes_logs WHERE id = ?');
            return stmt.get(id);
        } catch (error) {
            logger.error(`[MES日志] 获取ID ${id} 失败: ${error.message}`);
            return null;
        }
    }

    // 根据条件筛选MES日志
    queryMesLogs(filters = {}) {
        try {
            let query = 'SELECT * FROM mes_logs WHERE 1=1';
            const params = [];

            if (filters.eventType) {
                query += ' AND event_type = ?';
                params.push(filters.eventType);
            }

            if (filters.result) {
                query += ' AND result = ?';
                params.push(filters.result);
            }

            if (filters.dateFrom) {
                query += ' AND timestamp >= ?';
                params.push(filters.dateFrom);
            }

            if (filters.dateTo) {
                query += ' AND timestamp <= ?';
                params.push(filters.dateTo);
            }

            query += ' ORDER BY timestamp DESC';

            const stmt = this.db.prepare(query);
            return stmt.all(...params);
        } catch (error) {
            logger.error(`[MES日志] 查询失败: ${error.message}`);
            return [];
        }
    }

    // 清理旧日志（可选，保留最近N天的日志）
    cleanupOldLogs(daysToKeep = 30) {
        try {
            const stmt = this.db.prepare(`
                DELETE
                FROM mes_logs
                WHERE timestamp < datetime('now', 'localtime', '-' || ? || ' days')
            `);

            const info = stmt.run(daysToKeep);
            logger.info(`[MES日志] 已清理 ${info.changes} 条旧日志`);
            return info.changes;
        } catch (error) {
            logger.error(`[MES日志] 清理失败: ${error.message}`);
            return 0;
        }
    }

    // 导出日志为JSON
    exportLogsAsJson(filters = {}) {
        try {
            const logs = this.queryMesLogs(filters);
            return JSON.stringify(logs, null, 2);
        } catch (error) {
            logger.error(`[MES日志] 导出失败: ${error.message}`);
            return null;
        }
    }

    // 关闭数据库连接
    close() {
        if (this.db) {
            this.db.close();
            this.db = null;
            logger.info('数据库连接已关闭');
        }
    }
}

// 创建单例实例
export const mesLogger = new MesLogger();